package com.cdshangpai.utils.api;

import android.os.StrictMode;

import com.alibaba.fastjson.JSONObject;
import com.cdshangpai.utils.converts.JsonConvert;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

public class HttpRequest {
    private OkHttpClient okHttpClient=new OkHttpClient();
    public static HttpRequest instance=new HttpRequest();
    public OkHttpClient getOkhttpClient()
    {
        okHttpClient.setConnectTimeout(NetConfig.connectTimeout, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(NetConfig.readTimeout,TimeUnit.SECONDS);
        return okHttpClient;
    }

    public static void closeStrictMode() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
    }

    /**
     * 标准get请求
     * @param url
     * @param params
     * @param httpResponse
     */
    public void get(String url,Object params,HttpResponse httpResponse)
    {
        closeStrictMode();
        try
        {
            JSONObject datas=new JSONObject();
            if(params!=null)
            {
                datas = JsonConvert.bean2Json(params);
            }
            request(url,datas,false,httpResponse);
        }catch(Exception e){
            httpResponse.setSuccess(false);
            httpResponse.setErrmsg("请求处理错误，请稍后重试");
            httpResponse.callback();
        }

    }

    /**
     * 标准get请求
     * @param url
     * @param params
     * @param httpResponse
     */
    public void post(String url,Object params,HttpResponse httpResponse)
    {
        closeStrictMode();
        try
        {
            JSONObject datas=new JSONObject();
            if(params!=null)
            {
                datas = JsonConvert.bean2Json(params);
            }
            request(url,datas,true,httpResponse);
        }catch(Exception e){
            httpResponse.setSuccess(false);
            httpResponse.setErrmsg("请求处理错误，请稍后重试");
            httpResponse.callback();
        }

    }

    /**
     * 请求执行方法
     * @param url
     * @param params
     * @param json
     * @param httpResponse
     */
    private void request(String url, JSONObject params, Boolean json, HttpResponse httpResponse) throws Exception
    {
        String requestUrl=url;
        Request.Builder builder=new Request.Builder();
        if(json)
        {
            //json方式post请求
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            String requestDatas=params==null?"{}":params.toJSONString();
            RequestBody requestBody = RequestBody.create(JSON,requestDatas);

            builder=builder.url(requestUrl)
                    .post(requestBody);

        }
        else
        {
            //普通get请求
            String urlParam=fmtUrlParam(params);
            requestUrl+=urlParam.length()>0?urlParam:"";

            builder=builder.url(requestUrl);
        }

        Request request=builder.build();
        //请求参数构造完成

        //执行请求
        getOkhttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                httpResponse.setSuccess(false);
                httpResponse.setErrmsg("服务器连接失败，请稍后重试。");
                httpResponse.callback();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String responseData = response.body().string();
                httpResponse.setSuccess(true);
                httpResponse.setResponseData(responseData);
                httpResponse.callback();
            }
        });
    }


    /**
     * 获取url参数
     * @param params
     * @return
     * @throws Exception
     */
    private String fmtUrlParam(JSONObject params)
    {
        String result="";
        if(params!=null)
        {
            for(String key:params.keySet())
            {
                try
                {
                    Object temp=params.get(key);
                    if(temp!=null)
                    {
                        result+=key+"="+ URLEncoder.encode(temp.toString(),"utf-8")+"&";
                    }
                }
                catch(Exception e){

                }
            }
            if(result.length()>1)
            {
                int lastindex=result.length()-1;
                result="?"+result.substring(0,lastindex);
            }
        }
        return result;
    }
}